
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Expressions;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;

using System.Linq.Dynamic.Core;
 using Microsoft.EntityFrameworkCore; 


using DualControl.EmergencyMeasures.Dtos;
using DualControl.EmergencyMeasures;
using DualControl.HazardSources;
using DualControl.RiskPoints;
using Abp.Runtime.Session;
using DualControl.ControlMeasures.Dtos.CustomMapper;

namespace DualControl.EmergencyMeasures
{
    /// <summary>
    /// EmergencyMeasure应用层服务的接口实现方法  
    ///</summary>

    public class EmergencyMeasureAppService : DualControlAppServiceBase, IEmergencyMeasureAppService
    {
        private readonly IRepository<EmergencyMeasure, int> _emergencymeasureRepository;

        private readonly IRepository<HazardSource> _hazardsourceRepository;

        private readonly IRepository<RiskPoint> _riskpointrepository;


        /// <summary>
        /// 构造函数 
        ///</summary>
        public EmergencyMeasureAppService(
        IRepository<EmergencyMeasure, int>emergencymeasureRepository,
        IRepository<HazardSource> hazardsourceRepository,
        IRepository<RiskPoint> riskpointrepository
            )
        {
            _emergencymeasureRepository = emergencymeasureRepository;
            _hazardsourceRepository = hazardsourceRepository;
            _riskpointrepository = riskpointrepository;
        }

        /// <summary>
        /// 获取HazardSource的分页列表信息,包含应急措施信息
        /// 设计一个Hazardsources包含应急措施的Dto
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<HSEmergencyMeasureListDto>> GetPagedHSEmergencyMeasure(GetEmergencyMeasuresInput input)
        {
            var query = from hs in _hazardsourceRepository.GetAll().Include("EmergencyMeasures")
                        join rp in _riskpointrepository.GetAll() on hs.RiskPointId equals rp.Id
                        select new HSEmergencyMeasureListDto
                        {
                            Id = hs.Id,
                            //风险点
                            Code = rp.Code,
                            RiskPointId = rp.Id,
                            OrganizationUnitId = rp.OrganizationUnitId,
                            //部门名称,在前端转换

                            RiskPointName = rp.Name,
                            HazardSourceName = hs.HazardSourceName,
                            RiskFactor = hs.RiskFactor,
                            EmergencyMeasures = hs.EmergencyMeasures
                        };


            var hazardsourceCount = await query.CountAsync();
            
            var hazardsources = await query
                    .OrderBy(input.Sorting).AsNoTracking()
                    .PageBy(input)
                    .ToListAsync();

            // var hazardsourceListDtos = ObjectMapper.Map<List <HazardSourceListDto>>(hazardsources);
            var hazardsourceListDtos = hazardsources.MapTo<List<HSEmergencyMeasureListDto>>();

            return new PagedResultDto<HSEmergencyMeasureListDto>(
                hazardsourceCount, hazardsourceListDtos
                );
        }


       








        /// <summary>
        /// 获取EmergencyMeasure的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<EmergencyMeasureListDto>> GetPagedEmergencyMeasures(GetEmergencyMeasuresInput input)
        {

            var query = _emergencymeasureRepository.GetAll();
            // TODO:根据传入的参数添加过滤条件

            var emergencymeasureCount = await query.CountAsync();

            var emergencymeasures = await query
                    .OrderBy(input.Sorting).AsNoTracking()
                    .PageBy(input)
                    .ToListAsync();

            // var emergencymeasureListDtos = ObjectMapper.Map<List <EmergencyMeasureListDto>>(emergencymeasures);
            var emergencymeasureListDtos = emergencymeasures.MapTo<List<EmergencyMeasureListDto>>();

            return new PagedResultDto<EmergencyMeasureListDto>(
emergencymeasureCount,
emergencymeasureListDtos
                );
        }


        /// <summary>
        /// 通过指定id获取EmergencyMeasureListDto信息
        /// </summary>
        public async Task<EmergencyMeasureListDto> GetEmergencyMeasureByIdAsync(EntityDto<int> input)
        {
            var entity = await _emergencymeasureRepository.GetAsync(input.Id);

            return entity.MapTo<EmergencyMeasureListDto>();
        }

        /// <summary>
        /// MPA版本才会用到的方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<GetEmergencyMeasureForEditOutput> GetEmergencyMeasureForEdit(NullableIdDto<int> input)
        {
            var output = new GetEmergencyMeasureForEditOutput();
            EmergencyMeasureEditDto emergencymeasureEditDto;

            if (input.Id.HasValue)
            {
                var entity = await _emergencymeasureRepository.GetAsync(input.Id.Value);

                emergencymeasureEditDto = entity.MapTo<EmergencyMeasureEditDto>();

                //emergencymeasureEditDto = ObjectMapper.Map<List <emergencymeasureEditDto>>(entity);
            }
            else
            {
                emergencymeasureEditDto = new EmergencyMeasureEditDto();
            }

            output.EmergencyMeasure = emergencymeasureEditDto;
            return output;
        }


        /// <summary>
        /// 添加应急措施，一次可添加4条
        /// </summary>
        /// <param name="RiskPointId"></param>
        /// <param name="HazardSourceId"></param>
        /// <param name="ControlMeasures"></param>
        /// <returns></returns>
        public async Task InsertEmergencyMeasures(int RiskPointId, int HazardSourceId, string[] EmergencyMeasures)
        {
            var tenantid = AbpSession.GetTenantId();

            foreach (var emergencystring in EmergencyMeasures)
            {
                if (emergencystring.Length > 0)
                {
                    var controlMeasure = new EmergencyMeasure() { RiskPointId = RiskPointId, HazardSourceId = HazardSourceId, TenantId = tenantid,
                        EmergencyMeasuresContent = emergencystring
                    };
                    await _emergencymeasureRepository.InsertAsync(controlMeasure);
                }
            }

        }


        /// <summary>
        /// 手动添加，修改应急措施内容，只传递Id及措施内容
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task UpdateEmergencyMeasureContent(int Id,string Content)
        {
            var entity = await _emergencymeasureRepository.GetAsync(Id);
            entity.EmergencyMeasuresContent = Content;

            // ObjectMapper.Map(input, entity);
            await _emergencymeasureRepository.UpdateAsync(entity);
        }



        /// <summary>
        /// 添加或者修改EmergencyMeasure的公共方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task CreateOrUpdateEmergencyMeasure(CreateOrUpdateEmergencyMeasureInput input)
        {

            if (input.EmergencyMeasure.Id.HasValue)
            {
                await UpdateEmergencyMeasureAsync(input.EmergencyMeasure);
            }
            else
            {
                await CreateEmergencyMeasureAsync(input.EmergencyMeasure);
            }
        }



        /// <summary>
        /// 新增EmergencyMeasure
        /// </summary>

        protected virtual async Task<EmergencyMeasureEditDto> CreateEmergencyMeasureAsync(EmergencyMeasureEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = ObjectMapper.Map<EmergencyMeasure>(input);

            entity = await _emergencymeasureRepository.InsertAsync(entity);
            return entity.MapTo<EmergencyMeasureEditDto>();
        }

        



        /// <summary>
        /// 编辑EmergencyMeasure
        /// </summary>

        protected virtual async Task UpdateEmergencyMeasureAsync(EmergencyMeasureEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新

            var entity = await _emergencymeasureRepository.GetAsync(input.Id.Value);
            input.MapTo(entity);

            // ObjectMapper.Map(input, entity);
            await _emergencymeasureRepository.UpdateAsync(entity);
        }



        /// <summary>
        /// 删除EmergencyMeasure信息的方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>

        public async Task DeleteEmergencyMeasure(EntityDto<int> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _emergencymeasureRepository.DeleteAsync(input.Id);
        }



        /// <summary>
        /// 批量删除EmergencyMeasure的方法
        /// </summary>

        public async Task BatchDeleteEmergencyMeasuresAsync(List<int> input)
        {
            //TODO:批量删除前的逻辑判断，是否允许删除
            await _emergencymeasureRepository.DeleteAsync(s => input.Contains(s.Id));
        }


        /// <summary>
        /// 导出EmergencyMeasure为excel表,等待开发。
        /// </summary>
        /// <returns></returns>
        //public async Task<FileDto> GetEmergencyMeasuresToExcel()
        //{
        //	var users = await UserManager.Users.ToListAsync();
        //	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
        //	await FillRoleNames(userListDtos);
        //	return _userListExcelExporter.ExportToFile(userListDtos);
        //}



        //// custom codes

        //// custom codes end

    }
}


